import numpy as np
import logging
from collections import deque
from typing import Dict, Tuple, Optional
from dataclasses import dataclass
import sys
import os

# 添加项目根目录到Python路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(current_dir)
if project_root not in sys.path:
    sys.path.append(project_root)

from response.BrainWaveResult import BrainWaveResult

logger = logging.getLogger(__name__)

@dataclass
class BandConfig:
    """频段配置"""
    name: str
    frequency_range: Tuple[float, float]
    normal_range: Tuple[int, int]
    extreme_threshold: int
    smoothing_factor: float = 0.3

class FrequencyBandService:
    """
    多频段脑电波优化处理服务
    处理Alpha、Beta、Gamma波段的数值优化
    """
    
    def __init__(self, history_size: int = 10, outlier_threshold: float = 1.5):
        """
        初始化频段服务
        
        Args:
            history_size: 历史数据缓存大小
            outlier_threshold: 异常值检测阈值
        """
        self.history_size = history_size
        self.outlier_threshold = outlier_threshold
        
        # 配置各频段参数
        self.band_configs = {
            'alpha': BandConfig(
                name='Alpha',
                frequency_range=(8.0, 13.0),
                normal_range=(2000, 15000),
                extreme_threshold=30000,
                smoothing_factor=0.25
            ),
            'beta': BandConfig(
                name='Beta', 
                frequency_range=(13.0, 30.0),
                normal_range=(3000, 40000),
                extreme_threshold=100000,
                smoothing_factor=0.35
            ),
            'gamma': BandConfig(
                name='Gamma',
                frequency_range=(30.0, 100.0),
                normal_range=(1000, 25000),
                extreme_threshold=60000,
                smoothing_factor=0.4
            )
        }
        
        # 为每个频段创建历史数据缓存
        self.band_histories = {}
        self.raw_histories = {}
        self.last_valid_values = {}
        self.outlier_counts = {}
        self.total_counts = {}
        
        for band_name in self.band_configs.keys():
            self.band_histories[band_name] = deque(maxlen=history_size)
            self.raw_histories[band_name] = deque(maxlen=history_size)
            self.last_valid_values[band_name] = 0
            self.outlier_counts[band_name] = 0
            self.total_counts[band_name] = 0
    
    def process_frequency_bands(self, result: BrainWaveResult) -> BrainWaveResult:
        """
        处理多个频段数据 - 新版接口，直接接收和返回BrainWaveResult对象
        
        Args:
            result: BrainWaveResult对象，包含所有脑电数据
            
        Returns:
            BrainWaveResult: 处理后的脑电数据结果
        """
        # 提取需要处理的频段数据
        raw_data = {
            'alpha': result.alpha,
            'beta': result.beta,
            'gamma': result.gamma
        }
        
        # 处理各个频段
        processed_data = {}
        stats = {}
        
        for band_name, raw_value in raw_data.items():
            if band_name in self.band_configs:
                processed_value, band_stats = self._process_single_band(
                    band_name, raw_value, result.poorSignal
                )
                processed_data[band_name] = processed_value
                stats[band_name] = band_stats
        
        # 添加整体统计
        stats['overall'] = self._generate_overall_stats(processed_data, result.poorSignal)
        
        # 更新BrainWaveResult对象中的频段值
        result.update_band('alpha', processed_data['alpha'], "频段优化")
        result.update_band('beta', processed_data['beta'], "频段优化")
        result.update_band('gamma', processed_data['gamma'], "频段优化")
        
        # 添加处理步骤信息
        result.add_processing_step("band_optimization", {
            "statistics": stats
        })
        
        return result
    
    def process_frequency_bands_dict(self, raw_data: Dict[str, int], poor_signal: int = 0) -> Dict[str, any]:
        """
        处理多个频段数据 - 旧版接口，保持向后兼容
        
        Args:
            raw_data: 原始频段数据 {'alpha': value, 'beta': value, 'gamma': value}
            poor_signal: 信号质量
            
        Returns:
            dict: 处理后的数据和统计信息
        """
        processed_data = {}
        stats = {}
        
        for band_name, raw_value in raw_data.items():
            if band_name in self.band_configs:
                processed_value, band_stats = self._process_single_band(
                    band_name, raw_value, poor_signal
                )
                processed_data[band_name] = processed_value
                stats[band_name] = band_stats
        
        # 添加整体统计
        stats['overall'] = self._generate_overall_stats(processed_data, poor_signal)
        
        return {
            'processed_data': processed_data,
            'statistics': stats
        }
    
    def _process_single_band(self, band_name: str, raw_value: int, poor_signal: int) -> Tuple[int, dict]:
        """处理单个频段"""
        config = self.band_configs[band_name]
        self.total_counts[band_name] += 1
        self.raw_histories[band_name].append(raw_value)
        
        # 信号质量检查
        if poor_signal > 100:
            processed_value = self.last_valid_values[band_name]
            status = "信号质量差"
        else:
            processed_value = self._filter_band_outliers(band_name, raw_value)
            status = "正常处理"
        
        self.band_histories[band_name].append(processed_value)
        
        # 更新最后有效值
        if poor_signal <= 50:
            self.last_valid_values[band_name] = processed_value
        
        # 生成统计信息
        stats = self._generate_band_stats(band_name, raw_value, processed_value, status)
        
        return processed_value, stats
    
    def _filter_band_outliers(self, band_name: str, raw_value: int) -> int:
        """频段异常值过滤"""
        config = self.band_configs[band_name]
        
        # 极端值过滤
        if raw_value > config.extreme_threshold:
            self.outlier_counts[band_name] += 1
            return self.last_valid_values[band_name] if self.last_valid_values[band_name] > 0 else config.normal_range[0]
        
        # 超出正常范围的值也要过滤
        if raw_value > config.normal_range[1]:
            self.outlier_counts[band_name] += 1
            return self.last_valid_values[band_name] if self.last_valid_values[band_name] > 0 else config.normal_range[1]
        
        # 历史数据不足时的处理
        if len(self.band_histories[band_name]) < 3:
            return max(config.normal_range[0], min(raw_value, config.normal_range[1]))
        
        # 统计异常检测
        history_array = np.array(list(self.band_histories[band_name]))
        mean_value = np.mean(history_array)
        std_value = np.std(history_array)
        
        if std_value > 0:
            z_score = abs(raw_value - mean_value) / std_value
            if z_score > self.outlier_threshold:
                self.outlier_counts[band_name] += 1
                return int(mean_value)
        
        # 应用平滑滤波
        return self._apply_band_smoothing(band_name, raw_value)
    
    def _apply_band_smoothing(self, band_name: str, raw_value: int) -> int:
        """应用频段特定的平滑滤波"""
        config = self.band_configs[band_name]
        
        if len(self.band_histories[band_name]) < 1:
            return raw_value
        
        # 指数移动平均
        last_value = self.band_histories[band_name][-1]
        smoothed = int(config.smoothing_factor * raw_value + (1 - config.smoothing_factor) * last_value)
        
        return smoothed
    
    def _generate_band_stats(self, band_name: str, raw_value: int, processed_value: int, status: str) -> dict:
        """生成频段统计信息"""
        config = self.band_configs[band_name]
        outlier_rate = (self.outlier_counts[band_name] / self.total_counts[band_name] * 100) if self.total_counts[band_name] > 0 else 0
        
        # 频段状态评估
        band_state = self._evaluate_band_state(band_name, processed_value)
        
        return {
            'band_name': config.name,
            'frequency_range': f"{config.frequency_range[0]}-{config.frequency_range[1]}Hz",
            'raw_value': raw_value,
            'processed_value': processed_value,
            'status': status,
            'outlier_rate': round(outlier_rate, 1),
            'band_state': band_state,
            'reduction_ratio': round((1 - processed_value/raw_value) * 100, 1) if raw_value > 0 else 0
        }
    
    def _evaluate_band_state(self, band_name: str, value: int) -> str:
        """评估频段状态"""
        config = self.band_configs[band_name]
        
        if band_name == 'alpha':
            if value < 5000:
                return "低Alpha-紧张状态"
            elif value < 15000:
                return "正常Alpha-平静状态"
            elif value < 30000:
                return "高Alpha-放松状态"
            else:
                return "极高Alpha-深度放松"
                
        elif band_name == 'beta':
            if value < 8000:
                return "低Beta-困倦状态"
            elif value < 25000:
                return "正常Beta-清醒状态"
            elif value < 50000:
                return "高Beta-专注状态"
            else:
                return "极高Beta-焦虑状态"
                
        elif band_name == 'gamma':
            if value < 3000:
                return "低Gamma-低认知"
            elif value < 10000:
                return "正常Gamma-正常认知"
            elif value < 25000:
                return "高Gamma-高认知"
            else:
                return "极高Gamma-过度兴奋"
        
        return "未知状态"
    
    def _generate_overall_stats(self, processed_data: Dict[str, int], poor_signal: int) -> dict:
        """生成整体统计信息"""
        # 计算脑电活跃度指数
        alpha = processed_data.get('alpha', 0)
        beta = processed_data.get('beta', 0)
        gamma = processed_data.get('gamma', 0)
        
        # 简单的活跃度计算
        activity_index = (beta * 0.4 + gamma * 0.3 + alpha * 0.3) / 1000
        
        # 状态评估
        if poor_signal > 100:
            overall_state = "信号质量差"
        elif activity_index < 20:
            overall_state = "低活跃度"
        elif activity_index < 50:
            overall_state = "正常活跃度"
        elif activity_index < 80:
            overall_state = "高活跃度"
        else:
            overall_state = "极高活跃度"
        
        return {
            'activity_index': round(activity_index, 1),
            'overall_state': overall_state,
            'signal_quality': "良好" if poor_signal <= 50 else "一般" if poor_signal <= 100 else "差",
            'alpha_beta_ratio': round(alpha/beta, 2) if beta > 0 else 0,
            'beta_gamma_ratio': round(beta/gamma, 2) if gamma > 0 else 0
        }
    
    def get_band_trends(self) -> Dict[str, str]:
        """获取各频段变化趋势"""
        trends = {}
        
        for band_name in self.band_configs.keys():
            if len(self.band_histories[band_name]) < 5:
                trends[band_name] = "数据不足"
                continue
                
            recent = list(self.band_histories[band_name])[-5:]
            if recent[-1] > recent[0] * 1.15:
                trends[band_name] = "上升趋势"
            elif recent[-1] < recent[0] * 0.85:
                trends[band_name] = "下降趋势"
            else:
                trends[band_name] = "稳定状态"
        
        return trends
    
    def reset_all_histories(self):
        """重置所有历史数据"""
        for band_name in self.band_configs.keys():
            self.band_histories[band_name].clear()
            self.raw_histories[band_name].clear()
            self.outlier_counts[band_name] = 0
            self.total_counts[band_name] = 0
        
        logger.info("所有频段历史数据已重置")
        
    def reset_history(self):
        """重置历史数据 (兼容接口)"""
        self.reset_all_histories()